﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Windows.Forms;

namespace AAA.Forms.Components.Util
{
    public class DataGridViewComparer : IComparer
    {
        private List<string>[] _lstRefSorts;
        private string[] _strFieldNames;
        private bool _isLengthFirst;

        public bool IsLengthFirst
        {
            get { return _isLengthFirst; }
            set { _isLengthFirst = value; }
        }

        public DataGridViewComparer(string strFieldName, List<string> lstRefSort)
            : this(new string[] { strFieldName }, new List<string>[] { lstRefSort })
        {
        }

        public DataGridViewComparer(string[] strFieldNames, List<string>[] lstRefSorts)
        {
            _lstRefSorts = lstRefSorts;
            _strFieldNames = strFieldNames;
        }

        #region IComparer 成員

        public int Compare(object x, object y)
        {
            DataGridViewRow dataGridViewRow1 = (DataGridViewRow)x;
            DataGridViewRow dataGridViewRow2 = (DataGridViewRow)y;
            int iDiff;

            for (int i = 0; i < _strFieldNames.Length; i++)
            {
                if (_lstRefSorts[i] == null)
                {
                    iDiff = IsLengthFirst ? (dataGridViewRow1.Cells[_strFieldNames[i]].Value.ToString().Length != dataGridViewRow2.Cells[_strFieldNames[i]].Value.ToString().Length
                                                ?   dataGridViewRow1.Cells[_strFieldNames[i]].Value.ToString().Length - dataGridViewRow2.Cells[_strFieldNames[i]].Value.ToString().Length
                                                :   dataGridViewRow1.Cells[_strFieldNames[i]].Value.ToString().CompareTo(dataGridViewRow2.Cells[_strFieldNames[i]].Value.ToString()))
                                          : dataGridViewRow1.Cells[_strFieldNames[i]].Value.ToString().CompareTo(dataGridViewRow2.Cells[_strFieldNames[i]].Value.ToString());
                }
                else
                {
                    iDiff = _lstRefSorts[i].IndexOf(dataGridViewRow1.Cells[_strFieldNames[i]].Value == null ? "" : dataGridViewRow1.Cells[_strFieldNames[i]].Value.ToString()) -
                            _lstRefSorts[i].IndexOf(dataGridViewRow2.Cells[_strFieldNames[i]].Value == null ? "" : dataGridViewRow2.Cells[_strFieldNames[i]].Value.ToString());
                }
                if(iDiff != 0)
                    return iDiff;
            }

            return 0;
            //return _lstRefSort.IndexOf(dataGridViewRow1.Cells[_strFieldName].Value == null ? "" : dataGridViewRow1.Cells[_strFieldName].Value.ToString()) -
            //       _lstRefSort.IndexOf(dataGridViewRow2.Cells[_strFieldName].Value == null ? "" : dataGridViewRow2.Cells[_strFieldName].Value.ToString());

        }

        #endregion
    }
}
